//
//  LXOAuthViewController.m
//  微博
//
//  Created by imera on 15/9/21.
//  Copyright (c) 2015年 imera. All rights reserved.
//

#import "LXOAuthViewController.h"
#import "AFNetworking.h"
#import "LXAcount.h"
#import "LXViewController.h"
#import "LXNewFeatureViewController.h"
#import "LXWeiBoTool.h"
#import "MBProgressHUD+MJ.h"

@interface LXOAuthViewController()<UIWebViewDelegate>

@end

@implementation LXOAuthViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //1.添加授权页面
    UIWebView *webView = [[UIWebView alloc]init];
    webView.frame = self.view.bounds;
    webView.delegate = self;
    [self.view addSubview:webView];
    
    //2.加载授权页面
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",LXAppKey,LXRedirectUri];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

#pragma mark webview的代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD showMessage:@"哥正在帮你加载中..."];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUD];
}

/**
 *  当webview发送一个情求的时候都会调用，询问代理是否加载这个页面
 *
 *  @param request        请求的url地址
 *  @return 返回YES：访问；返回NO：不允许加载
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    
    NSRange range = [url rangeOfString:@"code="];
    if(range.length){
        long index = range.location + range.length;
        NSString *code = [url substringFromIndex:index];
        
        //1.创建请求管理对象
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        //说明服务器返回json数据
        mgr.responseSerializer = [AFJSONResponseSerializer serializer];
        
        //2.封装请求参数
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];

        params[@"client_id"] = LXAppKey;
        params[@"client_secret"] = LXClientSecret;
        params[@"grant_type"] = LXGrantType;
        params[@"code"] = code;
        params[@"redirect_uri"] = LXRedirectUri;
        
        [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [MBProgressHUD hideHUD];
            
            //将字典转为模型
            LXAcount *acount = [LXAcount accountWithDict:responseObject];
            
            //存储数据模型
            [LXAcount saveAcount:acount];
            
            //是否显示新特性界面
            [LXWeiBoTool chooseRootViewController];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD hideHUD];
        }];
        return NO;
    }
    
    return YES;
}

@end
